package com.easemob.helpdesk.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Message;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easemob.helpdesk.AppConfig;
import com.easemob.helpdesk.EMValueCallBack;
import com.easemob.helpdesk.activity.history.HistoryChatActivity;
import com.easemob.helpdesk.activity.history.SearchHistorySessionActivity;
import com.easemob.helpdesk.adapter.HistoryListAdapter;
import com.easemob.helpdesk.utils.DateUtils;
import com.easemob.helpdesk.utils.OnFreshCallbackListener;
import com.easemob.helpdesk.utils.TimeInfo;
import com.easemob.helpdesk.widget.recyclerview.DividerLine;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.R;
import com.hyphenate.kefusdk.HDDataCallBack;
//import com.hyphenate.kefusdk.bean.HistorySessionEntity;
//import com.hyphenate.kefusdk.bean.TechChannel;
//import com.hyphenate.kefusdk.entity.HDVisitorUser;
//import com.hyphenate.kefusdk.entity.HistorySessionScreenEntity;
import com.hyphenate.kefusdk.entity.HistorySessionEntity;
import com.hyphenate.kefusdk.entity.TechChannel;
import com.hyphenate.kefusdk.entity.option.HistorySessionScreenEntity;
import com.hyphenate.kefusdk.entity.user.HDVisitorUser;
import com.hyphenate.kefusdk.manager.session.HistorySessionManager;
import com.hyphenate.kefusdk.utils.HDLog;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;



import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link } subclass.
 */
public class HistorySessionFragment extends Fragment implements OnFreshCallbackListener {

    private static final String TAG = HistorySessionFragment.class.getSimpleName();

    private static final int MSG_LOAD_MORE_DATA = 0x01;
    private static final int MSG_REFRESH_DATA = 0x02;
    private static final int MSG_AUTHENTICATION = 0x03;
    private static final int PER_PAGE_SESSION_COUNT = 15;
    private static final int REQUEST_CODE_SCREENING = 16;

    private HistorySessionManager historySessionManager;



    public EasyRecyclerView recyclerView;

    private HistoryListAdapter mAdapter;
    private WeakHandler mWeakHandler;
    private  void initFindView(View view){
        recyclerView=view.findViewById(R.id.recyclerView);
        tvLabelTotalCount=view.findViewById(R.id.tv_label_total_count);
        search_button=view.findViewById(R.id.search_button);


    }
    public TextView tvLabelTotalCount;

    public RelativeLayout search_button;

//    @BindView(R.id.iv_filter)
//    public View viewFilter;

//    @BindView(R.id.rl_back)
//    public View viewBack;

    private TimeInfo currentTimeInfo;

    public static OnFreshCallbackListener callback = null;


    public HistorySessionFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_history_sessions, container, false);
        initFindView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        AppConfig.setFitWindowMode(this.getActivity());

        historySessionManager = new HistorySessionManager();
        /** 一周的历史会话消息 */
        currentTimeInfo = DateUtils.getTimeInfoByCurrentWeek(0);

        callback = this;

        historySessionManager.setCurrentTimeInfo(currentTimeInfo.getStartTime(), currentTimeInfo.getEndTime());
        initView();
        mWeakHandler = new WeakHandler(this);
        final LinearLayoutManager mLayoutManager = new LinearLayoutManager(this.getContext());
        recyclerView.setLayoutManager(mLayoutManager);
        //设置分割线
        DividerLine dividerLine = new DividerLine(DividerLine.VERTICAL);
        dividerLine.setSize(1);
        dividerLine.setColor(0xFFDDDDDD);
        recyclerView.addItemDecoration(dividerLine);

        recyclerView.getSwipeToRefresh().setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_dark, R.color.holo_orange_light, R.color.holo_red_light);
        recyclerView.setAdapterWithProgress(mAdapter = new HistoryListAdapter(this.getActivity()));
        mAdapter.setMore(R.layout.view_more, new RecyclerArrayAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMoreMethod();
            }
        });

//        mAdapter.setNoMore(R.layout.view_nomore);
        mAdapter.setError(R.layout.view_error).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                mAdapter.resumeMore();
            }
        });

        mAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int i) {
                if (i < 0 || i > mAdapter.getCount()){
                    return;
                }
                HistorySessionEntity entty = mAdapter.getItem(i);

                String sServiceId = entty.serviceSessionId;
                HDVisitorUser toUser = entty.visitorUser;
                Intent intent = new Intent();
                intent.setClass(getContext(), HistoryChatActivity.class);
                intent.putExtra("user", toUser);
                intent.putExtra("visitorid", sServiceId);
                intent.putExtra("originType", entty.orginType);
                intent.putExtra("techChannelName", entty.techChannelName);
                intent.putExtra("chatGroupId", Long.parseLong(String.valueOf(entty.chatGroupId)));
                startActivity(intent);
            }
        });

        recyclerView.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                onFreshData();
            }
        });
        mAdapter.addAll(historySessionManager.getList());

        mAdapter.sort(new Comparator<HistorySessionEntity>() {
            @Override
            public int compare(HistorySessionEntity lhs, HistorySessionEntity rhs) {
                if (lhs == null || rhs == null) {
                    return 0;
                }
                long ltime = convertStringTimeToLongTime(lhs.createDatetime);
                long rtime = convertStringTimeToLongTime(rhs.createDatetime);
                if (ltime < rtime) {
                    return 1;
                } else if (ltime > rtime) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        onFreshData();
    }

    public HistorySessionManager getHistorySessionManager(){
        return historySessionManager;
    }


    public void refreshLabelTotalCount(int count) {
//        if (tvLabelTotalCount != null) {
//            tvLabelTotalCount.setText("当前筛选结果 " + count + " (共 " + historySessionManager.getTotal_entries() + ")");
//        }
    }


    private void initView() {
//        viewFilter = findViewById(R.id.iv_filter);
//        viewBack = findViewById(R.id.rl_back);
//        recyclerView = (EasyRecyclerView) findViewById(R.id.recyclerView);
//        tvLabelTotalCount = (TextView) findViewById(R.id.tv_label_total_count);
//        search_button = (RelativeLayout)findViewById(R.id.search_button);

        search_button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                if(historySessionManager.getList().size() == 0){
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(getContext(), SearchHistorySessionActivity.class);
                intent.putParcelableArrayListExtra("list", historySessionManager.getList());

                startActivityForResult(intent, -1);
            }
        });
//        viewFilter.setOnClickListener(new View.OnClickListener(){
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent();
//                intent.setClass(HistorySessionActivity.this, ScreeningActivity.class);
//                intent.putExtra("timeinfo", currentTimeInfo);
//                intent.putExtra("showtag", true);
//                startActivityForResult(intent, REQUEST_CODE_SCREENING);
//            }
//        });

//        viewBack.setOnClickListener(new View.OnClickListener(){
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });

    }

    private void updateView(List<HistorySessionEntity> data) {
        if (data != null) {
            if (data.size() == 0) {
                mAdapter.stopMore();
                return;
            }
            mAdapter.addAll(data);
            refreshLabelTotalCount(mAdapter.getCount());
            if (data.size() < PER_PAGE_SESSION_COUNT) {
                mAdapter.stopMore();
                return;
            }
            mAdapter.pauseMore();
        }else {
            recyclerView.setRefreshing(false);
        }
    }


    private void refreshView(List<HistorySessionEntity> data) {
        if (data != null) {
            mAdapter.clear();
            mAdapter.addAll(data);
            refreshLabelTotalCount(mAdapter.getCount());
            if (data.size() < PER_PAGE_SESSION_COUNT) {
                mAdapter.stopMore();
                return;
            }
            mAdapter.pauseMore();
        }else{
            recyclerView.setRefreshing(false);
        }
    }

    @Override
    public void onFresh(EMValueCallBack callback) {
        onFreshData();
    }


    private static class WeakHandler extends android.os.Handler {
        WeakReference<HistorySessionFragment> weakReference;

        public WeakHandler(HistorySessionFragment activity) {
            this.weakReference = new WeakReference<HistorySessionFragment>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            HistorySessionFragment activity = weakReference.get();
            if (null != activity) {
                switch (msg.what) {
                    case MSG_LOAD_MORE_DATA:
                        activity.updateView((List<HistorySessionEntity>) msg.obj);
                        break;
                    case MSG_REFRESH_DATA:
                        activity.refreshView((List<HistorySessionEntity>) msg.obj);
                        break;
                    case MSG_AUTHENTICATION:
                        MainApplication.getInstance().getEventEmitter().sendEvent("logout");
                        break;
                    default:
                        break;
                }
            }


        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_SCREENING) {
                HistorySessionScreenEntity screenEntity = new HistorySessionScreenEntity();
                currentTimeInfo = (TimeInfo) data.getSerializableExtra("timeinfo");
                screenEntity.startTime = currentTimeInfo.getStartTime();
                screenEntity.endTime = currentTimeInfo.getEndTime();
                if(data.hasExtra("originType")){
                    screenEntity.currentOriginType = data.getStringExtra("originType");
                }
                if(data.hasExtra("techChannel")){
                    screenEntity.currentTechChannel = (TechChannel) data.getSerializableExtra("techChannel");
                }
                if(data.hasExtra("visitorName")){
                    screenEntity.currentVisitorName = data.getStringExtra("visitorName");
                }
                if (data.hasExtra("ids")) {
                    screenEntity.currentTagIds = data.getStringExtra("ids");
                }
                historySessionManager.setScreenOption(screenEntity);
                onFreshData();
            }

        }

    }


    // 2015-05-26 11:30:20
    private long convertStringTimeToLongTime(String stringTime) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        try {
            Date parseTime = dateFormat.parse(stringTime);
            return parseTime.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            HDLog.e(TAG, e.getMessage());
        }
        return 0;
    }

    @Override
    public void onDestroy() {
        mWeakHandler.removeCallbacksAndMessages(null);
        super.onDestroy();

        callback = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        callback = null;
    }

    public void onFreshData() {
        historySessionManager.getFirstPageSessionHistory(new HDDataCallBack<List<HistorySessionEntity>>() {
            @Override
            public void onSuccess(List<HistorySessionEntity> value) {
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_REFRESH_DATA;
                message.obj = value;
                mWeakHandler.sendMessage(message);
            }

            @Override
            public void onError(int error, String errorMsg) {
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_REFRESH_DATA;
                mWeakHandler.sendMessage(message);
            }

            @Override
            public void onAuthenticationException() {
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_AUTHENTICATION;
                mWeakHandler.sendMessage(message);
            }
        });
    }

    private void loadMoreMethod() {
        historySessionManager.loadMoreData(new HDDataCallBack<List<HistorySessionEntity>>() {
            @Override
            public void onSuccess(List<HistorySessionEntity> value) {
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_LOAD_MORE_DATA;
                message.obj = value;
                mWeakHandler.sendMessage(message);
            }

            @Override
            public void onError(int error, String errorMsg) {
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_LOAD_MORE_DATA;
                mWeakHandler.sendMessage(message);
            }

            @Override
            public void onAuthenticationException() {
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_AUTHENTICATION;
                mWeakHandler.sendMessage(message);
            }
        });
    }

}
